package org.i1510.wuyo.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.i1510.common.bean.PageBean;
import org.i1510.common.utils.DateUtils;
import org.i1510.common.utils.IDGenerator;
import org.i1510.common.utils.StringUtils;
import org.i1510.common.utils.UserUtils;
import org.i1510.common.utils.web.ResultMapper;
import org.i1510.common.utils.web.WebUtils;
import org.i1510.wuyo.dao.IKmRegistDao;
import org.i1510.wuyo.po.KmRegAnswer;
import org.i1510.wuyo.po.KmRegist;
import org.i1510.wuyo.service.IKmRegAnswerService;
import org.i1510.wuyo.service.IKmRegistService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;






@Controller
@RequestMapping(value = "/admin/km")
public class KmRegistController {
	private static final Logger logger = LoggerFactory.getLogger(KmRegistController.class);
	@Autowired
	private IKmRegistService iKmRegistService;
	@Autowired
	private IKmRegistDao iKmRegistDao;
	
	@Autowired
	private IKmRegAnswerService iKmRegAnswerService;
	
	private ResultMapper mapper;
	
	/**
	*@Author Rambo
	*@Desc：保存对象
	*@param kmRegist
	*@param errors
	*@return TODO
	*@Version  KmRegistController.java,v 1.1 2013-11-15 下午4:20:56 
	*/
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@ResponseBody
	public String save(@Valid @ModelAttribute("kmRegist") KmRegist kmRegist,String[] descAnswers,String[] kmAnswerIds,HttpServletRequest request,BindingResult errors) {
		
		if(errors.hasErrors()){			
			mapper = WebUtils.getMapper4Errors(errors);
		}else{
			mapper = iKmRegistService.save(kmRegist,request);
			if(null != mapper.getMap()){
				HashMap map = mapper.getMap();
				if(null != map.get("docId")){
					//docId所对应的答案设置为删除
					int count = iKmRegAnswerService.updateByKmRegistId("00", map.get("docId").toString());
					List<KmRegAnswer> list = new ArrayList<KmRegAnswer>();
					for (int i = 0; i < descAnswers.length; i++) {
						KmRegAnswer kra = new KmRegAnswer();
						if(kmAnswerIds.length > i){		
							kra = iKmRegAnswerService.findById(kmAnswerIds[i]);
							kra.setDocLastTime(DateUtils.getNow());
							kra.setDocLastor(UserUtils.getSessionUserBean(request).getSysUser().getDocId());
							kra.setDocStatus("");
						}else{
							kra.setDocId(IDGenerator.getGenerateID());		
							kra.setDocCreateTime(DateUtils.getNow());
							kra.setDocCreator(UserUtils.getSessionUserBean(request).getSysUser().getDocId());		
							kra.setDocStatus("");
						}
						kra.setDescAnswer(descAnswers[i]);
						kra.setKmRegistId(map.get("docId").toString());
						list.add(kra);
					}
					mapper = iKmRegAnswerService.saveAll(list);					
				}
			}
			
		}
		
		return mapper.toJson();
	}
	/**
	*@Author Rambo
	*@Desc：删除对象
	*@param docId
	*@param errors
	*@return TODO
	*@Version  KmRegistController.java,v 1.1 2014-9-2 下午3:38:17 
	*/
	@RequestMapping(value = "/deleteX", method = RequestMethod.POST)
	@ResponseBody
	public String deleteX(@Valid @ModelAttribute("docId") String docId,BindingResult errors) {
		
		if(errors.hasErrors()){			
			mapper = WebUtils.getMapper4Errors(errors);
		}else{
			mapper = iKmRegistService.delete(docId);
		}
		
		return mapper.toJson();
	}
	/**
	*@Author Rambo
	*@Desc：查看对象
	*@param docId
	*@param errors
	*@return TODO
	*@Version  KmRegistController.java,v 1.1 2014-9-2 下午3:39:35 
	*/
	@RequestMapping(value = "/view", method = RequestMethod.GET)
	@ResponseBody
	public String view(@Valid @ModelAttribute("docId") String docId,BindingResult errors) {
		ResultMapper mapperRtn = ResultMapper.generateFailure();
		if(errors.hasErrors()){			
			mapperRtn = WebUtils.getMapper4Errors(errors);
		}else{
			KmRegist kmRegist = iKmRegistService.findById(docId);
			mapperRtn = ResultMapper.generateSuccess();
			mapperRtn.appendResult("data", kmRegist);
			//获取答案
			Map conditions = new HashMap();
			conditions.put("kmRegistId", docId);
			List kmRegAnswers = iKmRegAnswerService.getAnswers(null, conditions);
			mapperRtn.appendResult("listData", kmRegAnswers);
		}		
		return mapperRtn.toJson();
	}
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	@ResponseBody
	public String list(@ModelAttribute("fromDate") String fromDate,@ModelAttribute("toDate") String toDate,@Valid @ModelAttribute("kmRegist") KmRegist kmRegist,@Valid @ModelAttribute("pageBean") PageBean pageBean,BindingResult errors) {
		ResultMapper mapperRtn = ResultMapper.generateFailure();
		if(errors.hasErrors()){			
			mapperRtn = WebUtils.getMapper4Errors(errors);
		}else{
			Map conditions = new HashMap();
			conditions.put("fromDate", fromDate);
			conditions.put("toDate", toDate);
			List  kmRegists = iKmRegistService.getPage(kmRegist, pageBean,conditions);
			int totalCount =  iKmRegistService.getPageCount(kmRegist,conditions);
			Map map = new HashMap();
			map.put("pageNo", pageBean.getPageNo());
			map.put("pageSize", pageBean.getPageSize());
			map.put("totalCount", totalCount);
			map.put("listData",kmRegists);
			
			mapperRtn = ResultMapper.generateSuccess();
			mapperRtn.appendResult("data", map);
		}		
		return mapperRtn.toJson();
	}
	/**
	*@Author Rambo
	*@Desc：状态修改
	*@param request
	*@param docId
	*@param docStatus
	*@param errors
	*@return TODO
	*@Version  CateController.java,v 1.1 2014-9-11 上午10:06:04 
	*/
	@RequestMapping(value = "/updateStatus", method = RequestMethod.POST)
	@ResponseBody
	public String updateStatus(HttpServletRequest request,@Valid @ModelAttribute("docId") String docId,@Valid @ModelAttribute("docStatus") String docStatus,BindingResult errors) {
		
		if(errors.hasErrors()){			
			mapper = WebUtils.getMapper4Errors(errors);
		}else{
			if(!StringUtils.isStringEmpty(docId)){
				KmRegist kmRegist = new KmRegist();
				
				kmRegist.setDocId(docId);
				kmRegist.setDocStatus(docStatus);
				mapper = iKmRegistService.save(kmRegist,request);
				int count = iKmRegAnswerService.updateByKmRegistId("00", docId);
			}else{
				mapper = ResultMapper.generateFailure();
				mapper.appendResult("messages", "无法找到该ID!");
			}
			
		}
		
		return mapper.toJson();
	}
	/**
	*@Author Rambo
	*@Desc：问题标题是否重复
	*@param request
	*@param title
	*@param errors
	*@return TODO
	*@Version  KmRegistController.java,v 1.1 2014-11-7 下午3:02:25 
	*/
	@RequestMapping(value = "/isReTitle", method = RequestMethod.POST)
	@ResponseBody
	public String isReTitle(HttpServletRequest request,@Valid @ModelAttribute("title") String title,BindingResult errors) {
		
		if(errors.hasErrors()){			
			mapper = WebUtils.getMapper4Errors(errors);
		}else{
			if(!StringUtils.isStringEmpty(title)){
				
				Map conditions = new HashMap();
				conditions.put("docSubject", title.trim());
				int totalCount =  iKmRegistService.getPageCount(null,conditions);
				if(totalCount <= 0){
					mapper = ResultMapper.generateSuccess();
				} else {
					mapper = ResultMapper.generateFailure();
					mapper.appendResult("messages", "问题标题重复!");
				}
			}else{
				mapper = ResultMapper.generateFailure();
				mapper.appendResult("messages", "无法找到问题!");
			}
			
		}
		
		return mapper.toJson();
	}
	/**
	*@Author Rambo
	*@Desc： 内容是否重复 
	*@param request
	*@param descs
	*@param errors
	*@return TODO
	*@Version  KmRegistController.java,v 1.1 2014-11-7 下午4:40:57 
	*/
	@RequestMapping(value = "/isReDesc", method = RequestMethod.POST)
	@ResponseBody
	public String isReDesc(HttpServletRequest request,@Valid @ModelAttribute("descs") String descs,BindingResult errors) {
		
		if(errors.hasErrors()){			
			mapper = WebUtils.getMapper4Errors(errors);
		}else{
			if(!StringUtils.isStringEmpty(descs)){
				
				Map conditions = new HashMap();
				conditions.put("descs", descs);
				int totalCount =  iKmRegistService.getPageCount(null,conditions);
				if(totalCount <= 0){
					mapper = ResultMapper.generateSuccess();
				} else {
					mapper = ResultMapper.generateFailure();
					mapper.appendResult("messages", "问题内容大部分重复!");
				}
			}else{
				mapper = ResultMapper.generateFailure();
				mapper.appendResult("messages", "无法找到问题!");
			}
			
		}
		
		return mapper.toJson();
	}
	@RequestMapping(value = "/similarList", method = RequestMethod.GET)
	@ResponseBody
	public String similarList(@Valid @ModelAttribute("docSubject") String docSubject,@Valid @ModelAttribute("pageBean") PageBean pageBean,BindingResult errors) {
		ResultMapper mapperRtn = ResultMapper.generateFailure();
		if(errors.hasErrors()){			
			mapperRtn = WebUtils.getMapper4Errors(errors);
		}else{
			Map conditions = new HashMap();
			conditions.put("docSubject_compare", docSubject);
			List  kmRegists = iKmRegistService.getPage(null, pageBean,conditions);
			int totalCount =  iKmRegistService.getPageCount(null,conditions);
			Map map = new HashMap();
			map.put("pageNo", pageBean.getPageNo());
			map.put("pageSize", pageBean.getPageSize());
			map.put("totalCount", totalCount);
			map.put("listData",kmRegists);
			
			mapperRtn = ResultMapper.generateSuccess();
			mapperRtn.appendResult("data", map);
		}		
		return mapperRtn.toJson();
	}
	/**
	*@Author Rambo
	*@Desc：答案加入此问题
	*@param request
	*@param kmId
	*@param appnedKmId
	*@param errors
	*@return TODO
	*@Version  KmRegistController.java,v 1.1 2014-11-7 下午5:26:57 
	*/
	@RequestMapping(value = "/joinAnswer", method = RequestMethod.POST)
	@ResponseBody
	public String joinAnswer(HttpServletRequest request,@Valid @ModelAttribute("kmId") String kmId,@Valid @ModelAttribute("appnedKmId") String appnedKmId,BindingResult errors) {
		
		if(errors.hasErrors()){			
			mapper = WebUtils.getMapper4Errors(errors);
		}else{
			if(!StringUtils.isStringEmpty(kmId)){
				//获取答案
				Map conditions = new HashMap();
				conditions.put("kmRegistId", kmId);
				List kmRegAnswers = iKmRegAnswerService.getAnswers(null, conditions);
				List<KmRegAnswer> list = new ArrayList<KmRegAnswer>();
				Map map = new HashMap();
				for(int i=0;i<kmRegAnswers.size();i++){
					map = (Map)(kmRegAnswers.get(i));
					KmRegAnswer kra = new KmRegAnswer();
					kra.setDocId(IDGenerator.getGenerateID());		
					kra.setDocCreateTime(DateUtils.getNow());
					kra.setDocCreator(UserUtils.getSessionUserBean(request).getSysUser().getDocId());		
					kra.setDocStatus("");
					kra.setDescAnswer(map.get("descAnswer")+"");
					kra.setKmRegistId(appnedKmId);
					list.add(kra);			
				
				}
				mapper = iKmRegAnswerService.saveAll(list);		
			}else{
				mapper = ResultMapper.generateFailure();
				mapper.appendResult("messages", "答案加入此问题失败!");
			}
			
		}
		
		return mapper.toJson();
	}
}